

import 'package:flutter/material.dart';
// import 'dart:async';

import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebPage extends StatefulWidget {
  String url;
  WebPage({Key key, this.url}) : super(key: key);

  @override
  _WebPageState createState() => _WebPageState(url);
}

class _WebPageState extends State<WebPage> {
  String url;
  _WebPageState(this.url);
  WebViewController _controller;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('',
            style: TextStyle(
                color: Colors.black)),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        elevation: 0.5,
      ),
      body: WebView(
        initialUrl: url,
        javascriptMode: JavascriptMode.unrestricted,
        navigationDelegate: (NavigationRequest request) {
          print(request.url);
          if (request.url.startsWith('alipay://')) {
          //   print('blocking navigation to $request}');
            _openApp(request.url);
            return NavigationDecision.prevent;
          }
          if (request.url.startsWith('weixin://')) {
          //   print('blocking navigation to $request}');
            _openApp(request.url);
            return NavigationDecision.prevent;
          }
          // print('allowing navigation to $request');
          return NavigationDecision.navigate;
        },
        onWebViewCreated: (WebViewController controller) {
          controller.canGoBack().then((res) {
            print(res); // 是否能返回上一级
          });
          controller.currentUrl().then((url) {
            print(url); // 返回当前url
          });
          controller.canGoForward().then((res) {
            print(res); //是否能前进
          });
          _controller = controller;
        },
        onPageFinished: (String value) {
          // webview 页面加载调用
        },
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    if (_controller != null) {
      _controller.currentUrl().then((url) {
        print(url); // 返回当前url
      });
    }
  }

  void _openApp(openurl) async {
    // Android
    print("open app");
    final url = 'vnd.' + openurl;
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      //  Ios
      final url = openurl;
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        throw 'Could not launch $url';
      }
    }
  }

  void dispose() {
    super.dispose();
  }
}
